
clear all
set more off
set mat 11000

set seed 913


capture program quan drop
program quan, eclass
	version 10.0
	syntax varlist(max=1) [, end(varname) instr(varlist) exog(varname) prone(varlist) tau(integer 50)] 
	tempname temp cutoff below prb moment resid
	local tau2=`tau'
	local tau=`tau'/100
	local cn=_N
		

	foreach num of numlist -.3(.01)1.3 {

		gen `temp'=`varlist'-`num'*`end'
		sort `temp'		
		gen `cutoff'=.5*`temp'[floor(_N*`tau')]+.5*`temp'[ceil(_N*`tau')]
		gen `below'=(`temp' <= `cutoff')

		probit `below' `prone'
		predict pr2
		gen `prb'=pr2
		drop pr2 
		
		local rrr=0
		local rrr2=0
		qui foreach var of varlist `instr' {	
			gen `moment'=`var' * (`below'-`prb')
			egen `resid'=sum(`moment')
			qui sum `resid'
			local rrr=(r(mean)/`cn')^2+`rrr'
			drop `moment' `resid'
		}


		if (`num'==-.3) {
			scalar residual1=`rrr'			
			local beta1=`num'
		}
		else {
			if (`rrr'<residual1) {
				local beta1=`num'
				scalar residual1=`rrr'

			}
		}
		drop `temp'-`prb'
	}

	ereturn scalar b1=`beta1'

	
end


set obs 500
set seed 913912411

gen hold=_n
qui foreach num of numlist 5(5)95 {
	matrix RRR`num'=J(1000,5,.)
}

foreach ttt of numlist 1/1000 {


display `ttt'

gen x5=1*uniform()
gen u1=.1*(uniform())+x5
sort u1
gen rk=(_n/_N)
gen x1=uniform()+u1
gen y=rk*(1+1*x1)

gen mdd=x1+1

counterfactual y x1 x5, method(logit) qlow(.05) qhigh(.96) qstep(.05) counterfactual(mdd x5) noboot nreg(250)
mat B=e(b)'
svmat B
qui foreach num of numlist 1/19 {
	local num2=5*`num'
	sum B1 if _n==`num'
	matrix RRR`num2'[`ttt',1]=r(mean)
}
drop B*

counterfactual y x1 x5, qlow(.05) qhigh(.96) qstep(.05) counterfactual(mdd x5) noboot 
mat B=e(b)'
svmat B
qui foreach num of numlist 1/19 {
	local num2=5*`num'
	sum B1 if _n==`num'
	matrix RRR`num2'[`ttt',2]=r(mean)
}
drop B*


foreach num of numlist 5(5)95 {


 	qui quan y, end(x1) prone(x5) instr(x1) tau(`num') 
	matrix RRR`num'[`ttt',3]=e(b1)


	qui qreg y x1 x5, quan(`num')
	matrix RRR`num'[`ttt',4]=_b[x1]

	qui qreg y x1, quan(`num')
	matrix RRR`num'[`ttt',5]=_b[x1]

}

drop x5-y mdd
}

clear
qui foreach num of numlist 5(5)95 {
	svmat RRR`num'
}
save Table2, replace


